/**
 * 
 */
package gpl.scotlandyard.android.services;

import gpl.scotlandyard.beans.basics.Node;
import gpl.scotlandyard.services.utils.MapLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.res.AssetManager;
import android.util.Log;

/**
 * @author Norbert
 */
public class MapLoaderService {

  private static final String TAG = MapLoaderService.class.toString();

  private final List<Listener> listeners = new ArrayList<Listener>();

  private final ArrayList<Node> map = new ArrayList<Node>();

  public void perform(final AssetManager assetManager, final String file) {
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        try {
          Log.i(TAG, "start job");
          BufferedReader bufr = new BufferedReader(new InputStreamReader(assetManager.open(file, AssetManager.ACCESS_BUFFER)));
          map.addAll(MapLoader.loadMap(bufr));
          Log.i(TAG, "end job");
          fireJobFinished();
        } catch (IOException e) {
          Log.w(TAG, "job failed on : " + e.toString());
          fireJobFailed(e);
        }
      }
    }, 500);
  }

  /**
   * @param listener
   */
  public void addListener(Listener listener) {
    listeners.add(listener);
  }

  /**
   * @param listener
   */
  public void removeListener(Listener listener) {
    listeners.remove(listener);
  }

  /**
   * 
   */
  private void fireJobFinished() {
    Log.d(TAG, "fireJobFinished");
    for (Listener listener : listeners) {
      listener.jobFinished(map);
    }
  }

  /**
   * @param e
   */
  private void fireJobFailed(Exception e) {
    Log.d(TAG, "fireJobFailed");
    for (Listener listener : listeners) {
      listener.jobFailed(e);
    }
  }

  public interface Listener {

    /**
     * @param map
     */
    void jobFinished(ArrayList<Node> map);

    /**
     * @param e
     */
    void jobFailed(Exception e);

  }

}
